﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace Silverlight.Windows.Controls
{
    public class ResizingGrid : Grid
    {
        FrameworkElement _rootVisual;

        public ResizingGrid()
            : base()
        {
            this.Loaded += GridLoaded;
            this.Unloaded += GridUnloaded;
        }

        void GridLoaded(object sender, RoutedEventArgs e)
        {
            if (Application.Current.IsRunningOutOfBrowser &&
                Application.Current.HasElevatedPermissions)
            {
                var window = Window.GetWindow(sender as DependencyObject);
                _rootVisual = window.Content;
            }
            else
            {
                _rootVisual = Application.Current.RootVisual as FrameworkElement;
            }
            _rootVisual.SizeChanged += ContentSizeChanged;
            SetHeight(_rootVisual.ActualHeight);
        }

        void GridUnloaded(object sender, RoutedEventArgs e)
        {
            _rootVisual.SizeChanged -= ContentSizeChanged;
        }

        void ContentSizeChanged(object sender, SizeChangedEventArgs e)
        {
            SetHeight(e.NewSize.Height);
        }

        private void SetHeight(double windowHeight)
        {
            var size = this.MeasureOverride(new Size(double.MaxValue,double.MaxValue));
            var contentHeight = size.Height;
            Height =
                windowHeight < contentHeight
                ? windowHeight
                : Double.NaN;
        }
    }
}
